#!/bin/bash

# 完整部署脚本
set -e

echo "=========================================="
echo "看广告免费兑换打印系统 - 完整部署脚本"
echo "=========================================="

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# 日志函数
log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检查必要工具
check_requirements() {
    log_info "检查部署环境..."
    
    # 检查Docker
    if ! command -v docker &> /dev/null; then
        log_error "Docker未安装，请先安装Docker"
        exit 1
    fi
    
    # 检查Docker Compose
    if ! command -v docker-compose &> /dev/null; then
        log_error "Docker Compose未安装，请先安装Docker Compose"
        exit 1
    fi
    
    # 检查Node.js
    if ! command -v node &> /dev/null; then
        log_error "Node.js未安装，请先安装Node.js"
        exit 1
    fi
    
    # 检查npm
    if ! command -v npm &> /dev/null; then
        log_error "npm未安装，请先安装npm"
        exit 1
    fi
    
    log_info "环境检查通过"
}

# 检查环境配置
check_config() {
    log_info "检查配置文件..."
    
    if [ ! -f .env.production ]; then
        log_error ".env.production 文件不存在，请先配置环境变量"
        exit 1
    fi
    
    # 加载环境变量
    source .env.production
    
    # 检查关键配置
    if [ -z "$MYSQL_ROOT_PASSWORD" ]; then
        log_error "MYSQL_ROOT_PASSWORD 未配置"
        exit 1
    fi
    
    if [ -z "$JWT_SECRET" ]; then
        log_error "JWT_SECRET 未配置"
        exit 1
    fi
    
    if [ -z "$DOMAIN" ]; then
        log_error "DOMAIN 未配置"
        exit 1
    fi
    
    log_info "配置检查通过"
}

# 构建前端
build_frontend() {
    log_info "构建前端应用..."
    
    cd frontend
    
    # 安装依赖
    log_info "安装前端依赖..."
    npm install
    
    # 构建H5版本
    log_info "构建H5版本..."
    npm run build:prod
    
    # 构建小程序版本
    log_info "构建微信小程序版本..."
    npm run build:mp-weixin:prod
    
    cd ..
    
    log_info "前端构建完成"
}

# 准备部署文件
prepare_deployment() {
    log_info "准备部署文件..."
    
    # 创建必要目录
    mkdir -p nginx/html
    mkdir -p nginx/logs
    mkdir -p nginx/ssl
    mkdir -p backend/logs
    mkdir -p backend/uploads
    
    # 复制前端构建文件
    if [ -d "frontend/dist" ]; then
        cp -r frontend/dist/* nginx/html/
        log_info "前端文件复制完成"
    else
        log_warn "前端构建文件不存在，跳过复制"
    fi
    
    # 设置权限
    chmod +x scripts/*.sh
    chmod 755 nginx/logs
    chmod 755 backend/logs
    chmod 755 backend/uploads
    chmod 700 nginx/ssl
    
    log_info "部署文件准备完成"
}

# 部署服务
deploy_services() {
    log_info "部署服务..."
    
    # 停止现有服务
    log_info "停止现有服务..."
    docker-compose down || true
    
    # 清理旧镜像（可选）
    if [ "$1" = "--clean" ]; then
        log_info "清理旧镜像..."
        docker system prune -f
    fi
    
    # 构建并启动服务
    log_info "构建并启动服务..."
    docker-compose up -d --build
    
    log_info "服务部署完成"
}

# 等待服务启动
wait_for_services() {
    log_info "等待服务启动..."
    
    # 等待数据库启动
    log_info "等待MySQL启动..."
    timeout=60
    while [ $timeout -gt 0 ]; do
        if docker-compose exec -T mysql mysqladmin ping -h localhost --silent; then
            log_info "MySQL已启动"
            break
        fi
        sleep 2
        timeout=$((timeout-2))
    done
    
    if [ $timeout -le 0 ]; then
        log_error "MySQL启动超时"
        exit 1
    fi
    
    # 等待Redis启动
    log_info "等待Redis启动..."
    timeout=30
    while [ $timeout -gt 0 ]; do
        if docker-compose exec -T redis redis-cli ping | grep -q PONG; then
            log_info "Redis已启动"
            break
        fi
        sleep 2
        timeout=$((timeout-2))
    done
    
    if [ $timeout -le 0 ]; then
        log_error "Redis启动超时"
        exit 1
    fi
    
    # 等待后端API启动
    log_info "等待后端API启动..."
    timeout=60
    while [ $timeout -gt 0 ]; do
        if curl -f -s http://localhost:3000/health > /dev/null; then
            log_info "后端API已启动"
            break
        fi
        sleep 2
        timeout=$((timeout-2))
    done
    
    if [ $timeout -le 0 ]; then
        log_error "后端API启动超时"
        exit 1
    fi
    
    log_info "所有服务已启动"
}

# 运行数据库迁移
run_migrations() {
    log_info "运行数据库迁移..."
    
    # 等待数据库完全就绪
    sleep 10
    
    # 运行迁移（如果有的话）
    # docker-compose exec backend npm run migrate
    
    log_info "数据库迁移完成"
}

# 健康检查
health_check() {
    log_info "执行健康检查..."
    
    # 检查服务状态
    log_info "检查Docker容器状态..."
    docker-compose ps
    
    # 检查后端健康状态
    log_info "检查后端API健康状态..."
    if curl -f -s http://localhost:3000/health/detailed | jq '.status' | grep -q "healthy"; then
        log_info "后端API健康检查通过"
    else
        log_warn "后端API健康检查失败"
    fi
    
    # 检查前端页面
    log_info "检查前端页面..."
    if curl -f -s http://localhost > /dev/null; then
        log_info "前端页面访问正常"
    else
        log_warn "前端页面访问失败"
    fi
    
    log_info "健康检查完成"
}

# 显示部署信息
show_deployment_info() {
    log_info "部署完成！"
    echo ""
    echo "=========================================="
    echo "部署信息"
    echo "=========================================="
    echo "前端地址: http://localhost"
    echo "API地址: http://localhost:3000"
    echo "健康检查: http://localhost:3000/health"
    echo ""
    echo "如果配置了域名和SSL："
    echo "前端地址: https://$DOMAIN"
    echo "API地址: https://api.$DOMAIN"
    echo ""
    echo "小程序构建文件位置: frontend/dist/build/mp-weixin"
    echo ""
    echo "=========================================="
    echo "后续步骤"
    echo "=========================================="
    echo "1. 配置域名DNS解析"
    echo "2. 配置SSL证书: ./scripts/setup-ssl.sh $DOMAIN"
    echo "3. 上传微信小程序: ./scripts/deploy-miniprogram.sh"
    echo "4. 设置监控和备份: ./scripts/setup-monitoring.sh"
    echo ""
}

# 主函数
main() {
    log_info "开始部署..."
    
    # 解析参数
    CLEAN_BUILD=false
    SKIP_FRONTEND=false
    
    while [[ $# -gt 0 ]]; do
        case $1 in
            --clean)
                CLEAN_BUILD=true
                shift
                ;;
            --skip-frontend)
                SKIP_FRONTEND=true
                shift
                ;;
            -h|--help)
                echo "用法: $0 [选项]"
                echo "选项:"
                echo "  --clean          清理旧镜像"
                echo "  --skip-frontend  跳过前端构建"
                echo "  -h, --help       显示帮助信息"
                exit 0
                ;;
            *)
                log_error "未知参数: $1"
                exit 1
                ;;
        esac
    done
    
    # 执行部署步骤
    check_requirements
    check_config
    
    if [ "$SKIP_FRONTEND" = false ]; then
        build_frontend
    fi
    
    prepare_deployment
    
    if [ "$CLEAN_BUILD" = true ]; then
        deploy_services --clean
    else
        deploy_services
    fi
    
    wait_for_services
    run_migrations
    health_check
    show_deployment_info
    
    log_info "部署完成！"
}

# 错误处理
trap 'log_error "部署失败，请检查错误信息"; exit 1' ERR

# 执行主函数
main "$@"